<template>
    <div class="login-page">
        <ValidateForm @form-submit="onFormSubmit">
            <div class="mb-3">
                <label for="exampleInputEmail1" class="form-label">邮箱地址</label>
                <validate-input type="email" id="exampleInputEmail1" aria-describedby="emailHelp" :rules="emailRules"
                    v-model="emailValue" placeholder="请输入邮箱地址">
                </validate-input>
            </div>
            <div class="mb-3">
                <label for="exampleInputPassword1" class="form-label">密码</label>
                <ValidateInput type="password" id="exampleInputPassword1" :rules="passwordRules" v-model="passwordValue"
                    placeholder="请输入密码"></ValidateInput>
            </div>
            <template v-slot:submit>
                <div class="d-grid gap-2 col-4 mx-auto">
                    <span class="btn btn-primary">Submit</span>
                </div>
            </template>
        </ValidateForm>
    </div>
</template>

<script lang="ts" setup>
import 'bootstrap/dist/css/bootstrap.min.css'
import {ref,provide} from 'vue'
import ValidateForm from '@/components/ValidateForm.vue';
import { RulesProp } from '@/utlis/type';
import {useRouter} from 'vue-router'
import { useStore } from 'vuex';
import ValidateInput from '@/components/ValidateInput.vue';
import createMessage from '@/components/createMessage';
//初始的邮箱和密码的值
const emailValue = ref('')
const passwordValue = ref('')
const router = useRouter()
const store = useStore()
//定义邮箱和密码的模版
const emailRules : RulesProp= [
  {type:'required',message:'电子邮箱地址不能为空'},
  {type:'email',message:'电子邮箱格式不正确'}
]
const passwordRules : RulesProp = [
  {type:'required',message:'密码不能为空'},
  {type:'password',message:'密码只包含数字'},
  {type:'range',message:'密码长度必须在6到12之间，且不能有空格',min:6,max:12},
]
//父组件的自定义事件,如果结果为true，则跳转到首页界面
const onFormSubmit = (result:boolean) =>{
  if(result){
    const payload = {
      email:emailValue.value,
      password:passwordValue.value
    }
    store.dispatch('loginAndFetch',payload).then(data =>{
      createMessage('登录成功，两秒以后跳转到首页！','success')
      setTimeout(()=>{
        router.push('/')
      },2000)
    }).catch(e =>{
      console.log(e)
    })
  }
}
</script>